const wxaapi = require('../../public/wxaapi.js');//api地址参数
const wxRequest = require('./../../utils/js/wxRequest.js'); //请求参数
const wxPromise = require('./../../utils/js/wxPromise.js').wxPromise;//promise信息
/**
 * 获取sessionKey   此时处于静默状态
 */
function fGetSessionKey(app,isFirst) {
  let _This = this;
  let sessionKey = app.globalData.sessionKey;
  return wxPromise(wx.checkSession)().then(result => {
    if (!isFirst && sessionKey&&result.errMsg.indexOf("ok") > 0) {
      return wxPromise(sessionKey);
    } else {
      return wxPromise(wx.login)().then(result => {
        let ucode = result.code;
        return wxRequest(wxaapi.unionid.code.url, { code: ucode });
      }).then(resSession => {
        /**
         * resSession {openid:"openid",session_key:"session_key",unionid:"unionid"}
         * */
        sessionKey = resSession.data.session_key;
        app.globalData.sessionKey = sessionKey;
        return wxPromise(sessionKey);
      });
    }
  });
};
/**
 * 用户授权用户信息 此时需要弹框显示
 */
function fAuthUserData(app,sessionKey){
  let _This = this;
  return wxPromise(wx.getUserInfo)().then(resUserInfo => {
    if (resUserInfo.errMsg.indexOf("ok") < 0) {
      let authData = {
        title: '微信授权',
        content: '为能正常使用小程序，请授权您的公开信息(昵称、头像等)',
        confirmText: "去授权"
      };
      return wxPromise(wx.showModal)(authData).then(ares => {
        if (ares.confirm) {
          return wxPromise(wx.openSetting)().then(settingResult => { //如果拒绝授权以后，提示用户，进行设置第二次授权
            if (settingResult.authSetting["scope.userInfo"]) {
              app.globalData.reauth = true;
            }
            return _This.fAuthUserData(sessionKey);
          });
        } else {
          //return _This.fAuthUserData(sessionKey);//强制重复授权，这是微信禁止的行为
        }
      });
    } else {
      var encryptedData = resUserInfo.encryptedData;
      var iv = resUserInfo.iv;
      var postData = {
        encryptedData: encryptedData,
        sessionKey: sessionKey, iv: iv
      };
      return wxRequest(wxaapi.unionid.userinfo.url, postData);
    }
  }).then(userResult => {
    if (userResult) {
      return userResult.data.userinfo;//赋值用户信息全局变量
    }
    return {};
  });
}


module.exports={
  fGetSessionKey, fAuthUserData
}